package cn.wk.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CoolFilter implements Filter {
    @Override
    //创建的时候，执行 ，只执行一次
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    //每次执行 都会被调用
    public void doFilter(ServletRequest rst, ServletResponse rsp, FilterChain chian) throws IOException, ServletException {
        HttpServletRequest request =(HttpServletRequest)rst;
        HttpServletResponse response=(HttpServletResponse) rsp;
        String url = request.getRequestURI();//得到url地址
        if(url.contains("/login.jsp")|| url.contains("/login")){
            chian.doFilter(rst,rsp);
        }else {
            //登录验证
            Object no = request.getSession().getAttribute("no");
            if(no!=null){
                //登录了放行
                chian.doFilter(rst,rsp);
            }else {
                request.getRequestDispatcher("/login.jsp").forward(request,response);
            }
        }

    }

    @Override
    //销毁
    public void destroy() {

    }
}
